﻿CREATE PROCEDURE [dbo].[WriteOffDocInsert]
(--списание товара
	@Id int output,
	@DocDate smalldatetime,
	@DocNumber varchar(20) output,
	@Note varchar(250),
	@MD datetime output,
	@MW varchar(50)
)
AS
DECLARE @DepartmentUserId int, @intRet int, @intNextId int
	SET NOCOUNT ON

IF @DocNumber Is Null
BEGIN
	EXEC [dbo].[GetNextDocNumber] 9, @intRet OUT
	SET @DocNumber = cast( @intRet as varchar(20))
END

IF @DocDate Is Null SET @DocDate = dbo.TodayDate() 
ELSE SET @DocDate = dbo.NormalizeDate(@DocDate)

IF @DepartmentUserId Is Null SELECT @DepartmentUserId = Id FROM CD.DepartmentUsers WHERE Login = suser_sname()

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT
--получение значения идентификатора
EXEC @intRet = dbo.GetNextCounterFor 'Documents', @intNextId OUTPUT
IF @intRet <> 0 RETURN @intRet

	SET NOCOUNT OFF;
INSERT INTO [CA].[Documents] (
Id, [DocTypeId], [DocDate], [DocNumber], [ContragentId], DepartmentUserId, 
[Note], [MD], [MW]) 
VALUES (@intNextId, 9, @DocDate, @DocNumber, 0, @DepartmentUserId, 
@Note, @MD, @MW);

SELECT @Id = @intNextId
--SELECT Id, GId, DocTypeId, DocDate, DocNumber, 
--ContragentId, DepartmentUserId, Note, MD, MW 
--FROM CA.Documents WHERE (Id = SCOPE_IDENTITY())

RETURN 0